<?php

    defined('BASEPATH') OR exit('No direct script access allowed');

    /**
     * Class ShopifyApi
     *
     * @property Shopify_api shopify_api
     */
    class ShopifyApi extends OAuth_Controller
    {

        public function products_down_page()
        {

            $this->load->model('siteweb_model');
            $this->load->model('shopify_url_model', '', false, array('type' => 1));
            $this->load->model('shopify_down_model', '', false, array('type' => 1));


            $assoc = $this->uri->uri_to_assoc();

            $siteweb = $this->siteweb_model->siteweb_info(array('web_name' => $assoc['web_name']));


            $this->load->library('shopify_api', $siteweb);

            $down_time = intval($this->shopify_down_model->shopify_down_time($siteweb['web_id']));

            $down_time = intval(strtotime('2019-1-1'));

            $products_count = $this->shopify_api->products_count($down_time);

            if ($products_count){
                $this->shopify_url_model->batch_shopify_url($products_count);
                $this->shopify_down_model->insert_shopify_down(array(
                                                                   'down_time' => time(),
                                                                   'type'      => 0,
                                                                   'web_id'    => $siteweb['web_id'],
                                                               ));
            }

        }

        public function products_down_content()
        {

            $this->load->model('siteweb_model');
            $this->load->model('shopify_goods_model');
            $this->load->model('shopify_url_model', '', false, array('type' => 1));
            $this->load->model('goods_model');
            $this->load->model('category_model');
            // $this->load->model('goods_sku_model');
            $assoc       = $this->uri->uri_to_assoc();
            $siteweb     = $this->siteweb_model->siteweb_info(array('web_name' => $assoc['web_name']));
            $shopify_url = $this->shopify_url_model->no_down_url($siteweb['web_id']);

            if ($shopify_url){
                $this->load->library('shopify_api', $siteweb);

                $products_arr = $this->shopify_api->products_data($shopify_url['shopify_url']);


                /*$config['upload_path'] = './album/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size'] = '100';
                $config['max_width'] = '1024';
                $config['max_height'] = '768';

                $this->load->library('upload', $config);
                $this->load->library('image_lib');


                //480*640图片
                $configLarge = array();
                $configLarge['image_library'] = 'gd2';
                $configLarge['source_image'] = '';
                $configLarge['create_thumb'] = TRUE;
                $configLarge['maintain_ratio'] = TRUE; //保持图片比例
                $configLarge['thumb_marker'] = '_big';
                $configLarge['width'] = 480;
                $configLarge['height'] = 640;
                //260*350图片
                $configThumb = array();
                $configThumb['image_library'] = 'gd2';
                $configThumb['source_image'] = '';
                $configThumb['create_thumb'] = TRUE;
                $configThumb['maintain_ratio'] = TRUE; //保持图片比例
                $configThumb['thumb_marker'] = '_small';
                $configThumb['width'] = 260;
                $configThumb['height'] = 350;*/

                if ($products_arr){

                    $time = time();
                    $i    = 1;

                    $products_arr = array_reverse($products_arr);
                    foreach ($products_arr as $row) {

                        $cate_id = $this->category_model->cate_id($row['product_type']);
                        if ($cate_id){
                            $row['cate_id'] = $cate_id;
                        }

                        $goods_sn = preg_replace('/[a-zA-Z]+/', 'ML', substr($row['variants'][0]['sku'], 0, -4));

                        if ($goods_sn){
                            $goods_id = $this->goods_model->goods_id(0, array('goods_sn' => $goods_sn));
                        }

                        $data = array(
                            'goods_name'   => trim($row['title']),
                            'cn_name'      => '',
                            'cat_id'       => intval($row['cate_id']),
                            'type_id'      => 0,
                            'suppliers_id' => 0,
                            'goods_sn'     => $goods_sn,
                            'supp_url'     => '',
                            'supp_sn'      => '',
                            'goods_weight' => '',
                            'in_price'     => 0.00,
                            'market_price' => 0.00,
                            'shop_price'   => trim($row['variants'][0]['price']),
                            'body_html'    => trim($row['body_html']),
                            'shopify_id'   => $row['id'],
                        );


                        $sku = array();

                        foreach ($row['variants'] as $_k => $variant) {
                            $sku[$_k]['sku_num_sn'] = preg_replace('/[a-zA-Z]+/', '', $variant['sku']);
                            $sku[$_k]['handle']     = 'insert';
                            $sku[$_k]['sku_sn']     = str_replace(' ', '', $variant['option2']) . '-' . $variant['option1'];
                            $sku[$_k]['sku_id']     = 0;
                        }

                        $data['sku'] = $sku;


                        $data['images'] = array();
                        foreach ($row['images'] as $image) {
                            $data['images'][] = array(
                                'file_name' => $image['src'],
                                'handle'    => 'insert',
                                'album_id'  => 0,
                            );
                        }
                        $data['supp'] = array();

                        $row['siteweb'] = $siteweb;

                        /*$row['image']['src'] = $this->upload->getImage($row['image']['src']);
                        $configThumb['source_image'] = $config['upload_path'] . $row['image']['src'];
                        $this->image_lib->initialize($configThumb);
                        $this->image_lib->resize();

                        $configLarge['source_image'] = $config['upload_path'] . $row['image']['src'];
                        $this->image_lib->initialize($configLarge);
                        $this->image_lib->resize();

                        foreach ($row['images'] as $k => $image) {
                            $row['images'][$k]['src'] = $this->upload->getImage($image['src']);
                            $configThumb['source_image'] = $config['upload_path'] . $image[$k]['src'];
                            $this->image_lib->initialize($configThumb);
                            $this->image_lib->resize();

                            $configLarge['source_image'] = $config['upload_path'] . $image[$k]['src'];
                            $this->image_lib->initialize($configLarge);
                            $this->image_lib->resize();
                        }*/


                        $row['goods_sn'] = $goods_sn;
                        if ( !$goods_id){
                            $goods_id = $this->goods_model->insert_shopify_goods($row);
                        }
                        $row['goods_id'] = $goods_id;
                        $row['web_id']   = $siteweb['web_id'];
                        $order           = $this->shopify_goods_model->insert_shopify_goods($row);
                        if ($order){

                            $i++;
                        }
                    }
                    $this->shopify_url_model->update_down_num(array('down_num' => $i), $shopify_url['shopify_id']);
                }
            }
        }

        /**
         * 获取需要拉取的订单
         * order_down_page
         * author: walker
         * Date: 2019/12/5
         * Time: 15:55
         * Note:
         */
        public function order_down_page()
        {
            $this->load->model('siteweb_model');
            $this->load->model('shopify_url_model');
            $this->load->model('shopify_down_model');
            $assoc   = $this->uri->uri_to_assoc();
            $siteweb = $this->siteweb_model->siteweb_info(array('web_name' => $assoc['web_name']));

            if ( !$siteweb){
                die('网址不存在！');
            }

            $this->load->library('shopify_api', $siteweb);
            $down_time = intval($this->shopify_down_model->shopify_down_time($siteweb['web_id']));

            $order_count = $this->shopify_api->order_count($down_time);

            if ($order_count){
                $this->shopify_url_model->batch_shopify_url($order_count);

                $this->shopify_down_model->insert_shopify_down(array(
                                                                   'down_time' => time(),
                                                                   'type'      => 0,
                                                                   'web_id'    => $siteweb['web_id'],
                                                               ));
            }
        }

        public function order_down_page_q()
        {
            $this->load->model('siteweb_model');
            $this->load->model('shopify_url_model');
            $this->load->model('shopify_down_model');
            $assoc   = $this->uri->uri_to_assoc();
            $siteweb = $this->siteweb_model->siteweb_info(array('web_name' => $assoc['web_name']));

            if ( !$siteweb){
                die('网址不存在！');
            }

            $this->load->library('shopify_api', $siteweb);

            $down_time = intval(strtotime('2016-1-1'));

            $order_count = $this->shopify_api->order_count($down_time);

            if ($order_count){
                $this->shopify_url_model->batch_shopify_url($order_count);

                $this->shopify_down_model->insert_shopify_down(array(
                                                                   'down_time' => time(),
                                                                   'type'      => 0,
                                                                   'web_id'    => $siteweb['web_id'],
                                                               ));
            }
        }

        /**
         * 拉取shopify订单
         * order_down_content
         * author: walker
         * Date: 2019/12/5
         * Time: 15:53
         * Note:
         */
        public function order_down_content()
        {

            $this->load->model('siteweb_model');
            $this->load->model('shopify_url_model');
            $this->load->model('order_model');
            $this->load->model('order_goods_model');
            $this->load->model('goods_sku_model');
            $this->load->model('customer_model');
            $this->load->model('purchase_goods_model');
            $this->load->model('purchase_order_model');
            $assoc = $this->uri->uri_to_assoc();

            $siteweb     = $this->siteweb_model->siteweb_info(array('web_name' => $assoc['web_name']));
            $shopify_url = $this->shopify_url_model->no_down_url($siteweb['web_id']);
            foreach ($shopify_url as $key => $value) {
            if ($value){
                $this->load->library('shopify_api', $siteweb);
                $order_arr = $this->shopify_api->order_data($value['shopify_url']);

                if ($order_arr === false){
                    exit(2);
                }

                $time = time();
                $i    = 1;

                if ($order_arr){

                    $order_arr = array_reverse($order_arr);
                    $order_ids = array();
                    foreach ($order_arr as $row) {
                        $order_id = $this->db->from('order_info')->where('order_sn', $row['order_number'])->where('web_id', $siteweb['web_id'])->select('order_id')->get()->row_array();
                        // $order_id = $this->order_model->order_id($row['order_number'], $siteweb['web_id']);
                        if ($order_id){
                            continue;
                        }
                        if (intval($row['order_number']) < 3462 && $siteweb['web_id'] == 1){
                            continue;
                        }

                        $row['u_id']        = $this->customer_model->user_id($row['customer']['id'], $siteweb['web_id']);
                        $row['time']        = time();
                        $row['web']         = $siteweb;
                        $row['m_goods_sku'] = $this->goods_sku_model;

                        $order_id = $this->order_model->insert_order($row);

                        $log_info = '';
                        if ($order_id){
                            $order_goods = $this->order_goods_model->goods_list($order_id);
                            if ($order_goods){
                                $log_info .= ($log_info ? '<br /> ' : '') . $this->goods_sku_model->order_occupy_sku($order_goods);
                            }
                            $order_goods = $this->order_goods_model->goods_list($order_id);
                            if ($order_goods){
                                $pg_ids = $this->purchase_goods_model->purchase_order_goods($order_goods);

                                foreach ($pg_ids as $rec_id => $pg) {
                                    $log_info .= ($log_info ? '<br /> ' : '') . "#{$pg['pg_id']} 往 #{$rec_id} 采购产品添加 {$pg['need_number']} 个采购";
                                }
                            }

                            if ($log_info){
                                $this->order_model->check_orders($order_id, 2, $log_info);
                            }

                            $order_ids[$order_id] = $order_id;

                            $i++;
                        }
                    }

                    if ($order_ids){
                        $purchase_goods = $this->purchase_goods_model->unallocated_goods_supp();
                        if ($purchase_goods){
                            $this->purchase_order_model->batch_create_order($purchase_goods);
                        }
                    }
                }

                echo $i;

                $this->shopify_url_model->update_down_num(array('down_num' => $i), $value['shopify_id']);
            }
            }
        }


        public function order_down_payment_no()
        {
            $this->load->model('siteweb_model');
            $this->load->model('shopify_url_model');
            $this->load->model('order_model');
            $assoc   = $this->uri->uri_to_assoc();
            $siteweb = $this->siteweb_model->siteweb_info(array('web_name' => $assoc['web_name']));

            $orders = $this->order_model->get_no_payment_no_order($siteweb['web_id']);


            if ($orders){
                $this->load->library('shopify_api', $siteweb);
                foreach ($orders as $row) {
                    $transactions = $this->shopify_api->order_payment_no($row['source_id']);


                    if ($transactions){
                        $data = array(
                            'order_id'   => $row['order_id'],
                            'payment_no' => $transactions['authorization'],
                            'trade_info' => serialize($transactions),
                        );
                        $this->order_model->update_payment_no($data);
                    }
                }
            }

        }

        public function mulan_upload_goods()
        {
            echo 111;
            exit;

            $this->load->model('siteweb_model');
            $this->load->model('goods_model');
            $this->load->model('shopify_goods_model');
            $this->load->model('goods_sku_model');
            $this->load->library('sys_message');

            $web_id = 1;

            $siteweb = $this->siteweb_model->siteweb_info(array('web_id' => $web_id));
            !$siteweb && $this->sys_message->wrong('网站不存在!');

            $this->load->library('shopify_api', $siteweb);


            $querey = $this->goods_model->db->from('goods')->where('shopify_id > 0')->get();

            foreach ($querey->result_array() as $goods) {
                $goods_sku = $this->goods_sku_model->sku_list(array('goods_id' => $goods['goods_id']), 1);

                $variants = array();
                foreach ($goods_sku as $row) {
                    $variants[] = array(
                        'option1' => $row['size'],
                        'option2' => $row['color'],
                        'sku'     => $siteweb['ab_name'] . ltrim($row['sku_num_sn'], 'ML'),
                        'price'   => $goods['shop_price'],
                    );
                }

                $data  = array(
                    'goods_id'     => $goods['goods_id'],
                    'goods_sn'     => $siteweb['ab_name'] . preg_replace("/[a-zA-Z]/", "", $goods['goods_sn']),
                    'web_id'       => $web_id,
                    'goods_name'   => $goods['goods_name'],
                    'cat_id'       => $goods['cat_id'],
                    'shop_price'   => $goods['shop_price'],
                    'market_price' => $goods['market_price'],
                    'body_html'    => $goods['body_html'],
                    'variants'     => serialize($variants),
                    'shopify_id'   => $goods['shopify_id'],
                    'tags'         => $goods['tags'],
                );
                $sg_id = $this->shopify_goods_model->add_goods($data);
            }
        }

        public function upload_goods()
        {
            $assoc = $this->uri->uri_to_assoc();
            $this->load->model('siteweb_model');
            $this->load->model('goods_model');
            $this->load->model('shopify_goods_model');
            $this->load->model('goods_sku_model');
            $this->load->library('sys_message');
            $this->load->model('tagslist_model');
            $goods_id  = intval($assoc['goods_id']);
            $goods_sku = $this->db->from('goods_sku')->where(['goods_id' => $goods_id, 'e_update' => 0, 'is_delete' => 0])->get()->result_array();
            if ($goods_sku){
                $this->sys_message->wrong('先上传SKU!');
            }

            if ($_POST){
                $web_ids = $this->input->post('web_id');
                if (empty($web_ids)){
                    $this->sys_message->wrong('请选择站点!');
                }

                $wrong = '';

                $this->load->library('shopify_api');

                $html = '';

                foreach ($web_ids as $value) {
                    $siteweb = $this->siteweb_model->siteweb_info(array('web_id' => $value));

                    !$siteweb && $this->sys_message->wrong('网站不存在!');
                    $this->shopify_api->initialize($siteweb);

                    $goods = $this->goods_model->goods_info($goods_id);
                    !$goods && $this->sys_message->wrong('产品不存在!');

                    $shopify_goods = $this->shopify_goods_model->goods_info(array('goods_id' => $goods_id, 'web_id' => $value));
                    $shopify_goods && $this->sys_message->wrong('产品已经上传过了!');

                    if ($shopify_goods){
                        $sg_id = $shopify_goods['sg_id'];
                    } else {
                        $goods_sku = $this->goods_model->get_goods_sku($goods_id, 1);

                        !$goods_sku && $this->sys_message->wrong('SKU不存在!');

                        $variants = array();
                        foreach ($goods_sku as $row) {
                            $variants[] = array(
                                'option1' => $row['size'],
                                'option2' => $row['color'],
                                'sku'     => $siteweb['ab_name'] . $row['sku_num_sn'],
                                'price'   => $goods['shop_price'],
                            );
                        }

                        $data = array(
                            'goods_id'     => $goods['goods_id'],
                            'goods_sn'     => $siteweb['ab_name'] . preg_replace("/[a-zA-Z]/", "", $goods['goods_sn']),
                            'web_id'       => $value,
                            'goods_name'   => $goods['goods_name'],
                            'cat_id'       => $goods['cat_id'],
                            'shop_price'   => $goods['shop_price'],
                            'market_price' => $goods['market_price'],
                            'body_html'    => $goods['body_html'],
                            'is_sales'     => 1,
                            'variants'     => $variants,
                            'tags'         => $this->tagslist_model->tags_in($goods['goods_id']),

                        );
                        $goods['goods_attr'] = json_decode($goods['goods_attr'], true);

                        if (empty($html) && $goods['goods_attr'] && count($goods['goods_attr']['attr_val']) > 1){
                            $html = '<table><tr>';
                            foreach ($goods['goods_attr']['attr_title'] as $attr_title) {
                                $html .= '<td>' . $attr_title . '</td>';
                            }
                            $html .= '</tr>';

                            $_attr = array();
                            foreach ($goods['goods_attr']['attr_val'] as $k => $_row) {
                                foreach ($_row as $_k => $_row_attr) {
                                    $_attr[$_k][$k] = $_row_attr;
                                }
                            }

                            foreach ($_attr as $k_val => $_attr_val) {
                                $html .= '<tr>';
                                foreach ($_attr_val as $k_title => $attr_title) {
                                    if ($k_title == 0){
                                        $html .= '<td>' . $attr_title . '</td>';
                                    } else {
                                        $attr_val = explode('-', $attr_title);

                                        $a1   = sprintf('%.1f', $attr_val[0] / 2.54);
                                        $a2   = $attr_val[1] ? ("-" . sprintf('%.1f', $attr_val[1] / 2.54)) : '';
                                        $html .= '<td>' . $a1 . $a2 . '(' . $attr_title . 'cm)' . '</td>';
                                    }
                                }
                                $html .= '</tr>';
                            }

                            /*foreach ($goods['goods_attr']['attr_val'] as $k_val => $_attr_val) {
                                $html .= '<tr>';
                                foreach ($goods['goods_attr']['attr_title'] as $k_title => $attr_title) {
                                    if ($goods['goods_attr']['attr_val'][$k_title][$k_val]) {
                                        if ($k_title == 0) {
                                            $html .= '<td>' . $goods['goods_attr']['attr_val'][$k_title][$k_val] . '</td>';
                                        } else {
                                            $attr_val = explode('-', $goods['goods_attr']['attr_val'][$k_title][$k_val]);

                                            $a1 = sprintf('%.1f', $attr_val[0] / 2.54);
                                            $a2 = $attr_val[1] ? ("-" . sprintf('%.1f', $attr_val[1] / 2.54)) : '';
                                            $html .= '<td>' . $a1 . $a2 . '</td>';
                                        }
                                    }

                                }
                                $html .= '</tr>';
                            }*/

                            $html .= '</table>';
                        }


                        $data['body_html'] .= $html;


                        $sg_id = $this->shopify_goods_model->insert_goods($data);

                    }

                    if ($sg_id){
                        $shopify_data = $this->shopify_goods_model->up_shopify_data($sg_id);

                        $response = $this->shopify_api->upload_goods($shopify_data);

                        if ($response){

                            $shopify_goods_data = array(
                                'shopify_id'  => $response['id'],
                                'update_time' => 0,
                            );
                            $this->shopify_goods_model->update_goods($sg_id, $shopify_goods_data);
                            //处理shopify图片ID
                            foreach ($shopify_data['images'] as $key => $value) {
                                //shopify 图片
                                $this->db->where(['album_url' => substr($value['src'], 22)]);
                                $this->db->update('goods_sku', ['img_shopify_id' => $response['images'][$key]['id']]);
                            }
                            //处理shopify sku ID
                            foreach ($shopify_data['variants'] as $key => $value) {
                                foreach ($response['variants'] as $k => $v) {
                                    if ($v['sku'] == $value['sku']){
                                        $this->db->where(['sku_num_sn' => substr($value['sku'], 2)]);
                                        $this->db->update('goods_sku', ['sku_shopify_id' => $v['id']]);
                                    }
                                }
                            }
                            //上传SKU图片
                            $img_shopify_id = $this->db->from('goods_sku')->where(['goods_id' => $shopify_data['goods_id']])->select('img_shopify_id')->group_by('img_shopify_id')->get()->result_array();
                            foreach ($img_shopify_id as $key => $value) {
                                if (empty($value['img_shopify_id'])){
                                    continue;
                                }

                                $sku_shopify_id = $this->db->from('goods_sku')->where(['img_shopify_id' => $value['img_shopify_id']])->select('sku_shopify_id')->get()->result_array();
                                $variant_ids    = [];

                                foreach ($sku_shopify_id as $k => $v) {
                                    $variant_ids[] = $v['sku_shopify_id'];
                                }
                                $res = array('image' => array('id' => $value['img_shopify_id'], 'variant_ids' => $variant_ids));
                                $this->shopify_api->shopify_sku_img($response['id'], $value['img_shopify_id'], $res);
                            }
                            //$order = $this->shopify_goods_model->insert_shopify_goods($response);

                        } else {
                            $wrong = $siteweb['web_name'] . '失败!';
                            break;
                        }
                    }
                }

                if ($wrong){
                    $this->sys_message->success($wrong);
                } else {
                    $this->sys_message->success('成功!');
                }

            }

            $this->sys_message->wrong('上传失败!');
        }


        //    public function upload_goods_bak()
        //    {
        //        $assoc = $this->uri->uri_to_assoc();
        //        $this->load->model('siteweb_model');
        //        $this->load->model('goods_model');
        //        $this->load->model('shopify_goods_model');
        //        $this->load->model('goods_sku_model');
        //        $this->load->library('sys_message');
        //        $this->load->model('tagslist_model');
        //        $goods_id = intval($assoc['goods_id']);
        //        $goods_sku = $this->db->from('goods_sku')->where(['goods_id'=>$goods_id,'e_update'=>0,'is_delete'=>0])->get()->result_array();
        //        if($goods_sku){
        //            $this->sys_message->wrong('先上传SKU!');
        //        }
        //
        //        if ($_POST) {
        //            $web_id = intval($this->input->post('web_id'));
        //
        //            $siteweb = $this->siteweb_model->siteweb_info(array('web_id' => $web_id));
        //            !$siteweb && $this->sys_message->wrong('网站不存在!');
        //
        //            $this->load->library('shopify_api', $siteweb);
        //
        //            $goods = $this->goods_model->goods_info($goods_id);
        //            !$goods && $this->sys_message->wrong('产品不存在!');
        //
        //            $shopify_goods = $this->shopify_goods_model->goods_info(array('goods_id' => $goods_id, 'web_id' => $web_id));
        //            $shopify_goods && $this->sys_message->wrong('产品已经上传过了!');
        //
        //            if ($shopify_goods) {
        //                $sg_id = $shopify_goods['sg_id'];
        //            } else {
        //                $goods_sku = $this->goods_model->get_goods_sku($goods_id, 1);
        //
        //                !$goods_sku && $this->sys_message->wrong('SKU不存在!');
        //
        //                $variants = array();
        //                foreach ($goods_sku as $row) {
        //                    $variants[] = array(
        //                        'option1' => $row['size'],
        //                        'option2' => $row['color'],
        //                        'sku' => $siteweb['ab_name'] . $row['sku_num_sn'],
        //                        'price' => $goods['shop_price']
        //                    );
        //                }
        //
        //                $data = array(
        //                    'goods_id' => $goods['goods_id'],
        //                    'goods_sn' => $siteweb['ab_name'] . preg_replace("/[a-zA-Z]/","",$goods['goods_sn']),
        //                    'web_id' => $web_id,
        //                    'goods_name' => $goods['goods_name'],
        //                    'cat_id' => $goods['cat_id'],
        //                    'shop_price' => $goods['shop_price'],
        //                    'market_price' => $goods['market_price'],
        //                    'body_html' => $goods['body_html'],
        //                    'is_sales' => 1,
        //                    'variants' => $variants,
        //                    'tags' => $this->tagslist_model->tags_in($goods['tags'])
        //
        //                );
        //
        //                $goods['goods_attr'] = json_decode($goods['goods_attr'], true);
        //                if ($goods['goods_attr'] && count($goods['goods_attr']['attr_val']) > 1) {
        //                    $html = '<table><tr>';
        //                    foreach ($goods['goods_attr']['attr_title'] as $attr_title) {
        //                        $html .= '<td>' . $attr_title . '</td>';
        //                    }
        //                    $html .= '</tr>';
        //
        //                    $_attr = array();
        //                    foreach ($goods['goods_attr']['attr_val'] as $k => $_row) {
        //                        foreach ($_row as $_k => $_row_attr) {
        //                            $_attr[$_k][$k] = $_row_attr;
        //                        }
        //                    }
        //
        //                    foreach ($_attr as $k_val => $_attr_val) {
        //                        $html .= '<tr>';
        //                        foreach ($_attr_val as $k_title => $attr_title) {
        //                            if ($k_title == 0) {
        //                                $html .= '<td>' . $attr_title . '</td>';
        //                            } else {
        //                                $attr_val = explode('-', $attr_title);
        //
        //                                $a1 = sprintf('%.1f', $attr_val[0] / 2.54);
        //                                $a2 = $attr_val[1] ? ("-" . sprintf('%.1f', $attr_val[1] / 2.54)) : '';
        //                                $html .= '<td>' . $a1 . $a2 . '(' . $attr_title . 'cm)' . '</td>';
        //                            }
        //                        }
        //                        $html .= '</tr>';
        //                    }
        //
        //
        //                    /*foreach ($goods['goods_attr']['attr_val'] as $k_val => $_attr_val) {
        //                        $html .= '<tr>';
        //                        foreach ($goods['goods_attr']['attr_title'] as $k_title => $attr_title) {
        //                            if ($goods['goods_attr']['attr_val'][$k_title][$k_val]) {
        //                                if ($k_title == 0) {
        //                                    $html .= '<td>' . $goods['goods_attr']['attr_val'][$k_title][$k_val] . '</td>';
        //                                } else {
        //                                    $attr_val = explode('-', $goods['goods_attr']['attr_val'][$k_title][$k_val]);
        //
        //                                    $a1 = sprintf('%.1f', $attr_val[0] / 2.54);
        //                                    $a2 = $attr_val[1] ? ("-" . sprintf('%.1f', $attr_val[1] / 2.54)) : '';
        //                                    $html .= '<td>' . $a1 . $a2 . '</td>';
        //                                }
        //                            }
        //
        //                        }
        //                        $html .= '</tr>';
        //                    }*/
        //
        //                    $html .= '</table>';
        //                    $data['body_html'] .= $html;
        //                }
        //
        //
        //                $sg_id = $this->shopify_goods_model->insert_goods($data);
        //            }
        //
        //
        //            if ($sg_id) {
        //
        //                $shopify_data = $this->shopify_goods_model->up_shopify_data($sg_id);
        //
        //                $response = $this->shopify_api->upload_goods($shopify_data);
        //
        //                if ($response) {
        //
        //                    $shopify_goods_data = array(
        //                        'shopify_id' => $response['id'],
        //                        'update_time' => 0
        //                    );
        //                    $this->shopify_goods_model->update_goods($sg_id, $shopify_goods_data);
        //                    //处理shopify图片ID
        //                    foreach ($shopify_data['images'] as $key => $value) {
        //                        //shopify 图片
        //                        $this->db->where(['album_url'=>substr($value['src'],22)]);
        //                        $this->db->update('goods_sku',['img_shopify_id'=>$response['images'][$key]['id']]);
        //                    }
        //                    //处理shopify sku ID
        //                    foreach($shopify_data['variants'] as $key => $value){
        //                        foreach ($response['variants'] as $k => $v) {
        //                            if($v['sku'] == $value['sku']){
        //                                $this->db->where(['sku_num_sn'=>substr($value['sku'],2)]);
        //                                $this->db->update('goods_sku',['sku_shopify_id'=>$v['id']]);
        //                            }
        //                        }
        //                    }
        //                    //上传SKU图片
        //                    $img_shopify_id = $this->db->from('goods_sku')->where(['goods_id'=>$shopify_data['goods_id']])->select('img_shopify_id')->group_by('img_shopify_id')->get()->result_array();
        //                    foreach ($img_shopify_id as $key => $value) {
        //                        if(empty($value['img_shopify_id'])){
        //                            continue;
        //                        }
        //
        //                        $sku_shopify_id = $this->db->from('goods_sku')->where(['img_shopify_id'=>$value['img_shopify_id']])->select('sku_shopify_id')->get()->result_array();
        //                        $variant_ids = [];
        //
        //                        foreach ($sku_shopify_id as $k => $v) {
        //                            $variant_ids[] = $v['sku_shopify_id'];
        //                        }
        //                        $res = array('image'=>array('id'=>$value['img_shopify_id'],'variant_ids'=>$variant_ids));
        //                        $this->shopify_api->shopify_sku_img($response['id'],$value['img_shopify_id'],$res);
        //                    }
        //                    //$order = $this->shopify_goods_model->insert_shopify_goods($response);
        //
        //                    $this->sys_message->success('成功!');
        //                }
        //
        //            }
        //        }
        //
        //        $this->sys_message->wrong('上传失败!');
        //    }

        /*
         *孙坚
         *2019/4/13
         *产品列表批量上传
        */
        public function upload_goods_batch()
        {


            $this->load->model('siteweb_model');
            $this->load->model('goods_model');
            $this->load->model('shopify_goods_model');
            $this->load->model('goods_sku_model');
            $this->load->library('sys_message');
            $this->load->library('shopify_api');


            if ($_POST){
                $web_id = intval($this->input->post('web_id'));

                $goods_ids = trim($this->input->post('cgoods'));

                $siteweb = $this->siteweb_model->siteweb_info(array('web_id' => $web_id));
                !$siteweb && $this->sys_message->wrong('网站不存在!');

                $goods_list = $this->goods_model->goods_up_shopify_list($goods_ids);

                foreach ($goods_list as $goods) {
                    $shopify_goods = $this->shopify_goods_model->goods_info(array('goods_id' => $goods['goods_id'], 'web_id' => $web_id));

                    if ($shopify_goods){
                        continue;
                    }

                    $goods_sku = $this->goods_model->get_goods_sku($goods['goods_id'], 1);
                    if (empty($goods_sku)){
                        continue;
                    }
                    $variants = array();
                    foreach ($goods_sku as $row) {
                        $variants[] = array(
                            'option1' => $row['size'],
                            'option2' => $row['color'],
                            'sku'     => $siteweb['ab_name'] . $row['sku_num_sn'],
                            'price'   => $goods['shop_price'],
                        );
                    }

                    $goods['goods_attr'] = json_decode($goods['goods_attr'], true);
                    if ($goods['goods_attr'] && count($goods['goods_attr']['attr_val']) > 1){
                        $html = '<table><tr>';
                        foreach ($goods['goods_attr']['attr_title'] as $attr_title) {
                            $html .= '<td>' . $attr_title . '</td>';
                        }
                        $html .= '</tr>';

                        $_attr = array();
                        foreach ($goods['goods_attr']['attr_val'] as $k => $_row) {
                            foreach ($_row as $_k => $_row_attr) {
                                $_attr[$_k][$k] = $_row_attr;
                            }
                        }

                        foreach ($_attr as $k_val => $_attr_val) {
                            $html .= '<tr>';
                            foreach ($_attr_val as $k_title => $attr_title) {
                                if ($k_title == 0){
                                    $html .= '<td>' . $attr_title . '</td>';
                                } else {
                                    $attr_val = explode('-', $attr_title);

                                    $a1   = sprintf('%.1f', $attr_val[0] / 2.54);
                                    $a2   = $attr_val[1] ? ("-" . sprintf('%.1f', $attr_val[1] / 2.54)) : '';
                                    $html .= '<td>' . $a1 . $a2 . '(' . $attr_title . 'cm)' . '</td>';
                                }
                            }
                            $html .= '</tr>';
                        }

                        $html .= '</table>';
                    }

                    $data = array(
                        'goods_id'     => $goods['goods_id'],
                        'goods_sn'     => $siteweb['ab_name'] . $goods['goods_sn'],
                        'web_id'       => $web_id,
                        'goods_name'   => "{$siteweb['title']} " . $goods['goods_name'],
                        'cat_id'       => $goods['cat_id'],
                        'shop_price'   => $goods['shop_price'],
                        'market_price' => $goods['market_price'],
                        'body_html'    => $goods['body_html'] . $html,
                        'is_sales'     => 1,
                        'variants'     => $variants,
                        'tags'         => $goods['tags'],
                    );
                    $this->shopify_goods_model->insert_goods($data);

                }
            }

            $this->sys_message->success('成功!');
            //$this->sys_message->wrong('上传失败!');

        }

        /*
         *孙坚
         *2019/4/13
         *定时检查没有上传成功的产品
        */
        public function timing_up_product_status()
        {
            $this->load->model('shopify_goods_model');
            $this->shopify_goods_model->select_up_shopify();
        }


        public function upg_goods()
        {

            $this->load->model('siteweb_model');
            $siteweb = $this->siteweb_model->siteweb_info(array('web_id' => 1));
            !$siteweb && $this->sys_message->wrong('网站不存在!');

            $this->load->library('shopify_api', $siteweb);

            $down_time = strtotime(' -28 hours');

            $post_data = array(
                'act'       => 'order_synchrodata',
                'order_ids' => '2020542,2020641,2017017,2020648,2010942,2020653,2020659,2020660,2020661',
                'key'       => '92b264daf4da8d13a1ca390d6d49b4b1',
            );
            $post_url  = 'http://erp.lovelywholesale.com/lovelyErpAdm2015/dptai.php';
            //print_r($post_data);
            //print_r($post_url);
            $order_json = $this->shopify_api->shopify_curl($post_url, $post_data, 'POST');

            echo $order_json;
            $order_arr = json_decode($order_json, true);
        }

        public function up_sg_goods()
        {

            $this->load->model('shopify_goods_model');
            $this->load->library('sys_message');
            $this->load->model('siteweb_model');
            $assoc = $this->uri->uri_to_assoc();

            $sg_id = intval($assoc['sg_id']);

            $shopify_data = $this->shopify_goods_model->up_shopify_data($sg_id);

            !$shopify_data && $this->sys_message->wrong('产品不存在!');
            //shopify_data 商品信息
            //$shopify_data['shopify_id'] > 0 && $this->sys_message->wrong('产品已经上传过了!');

            $siteweb = $this->siteweb_model->siteweb_info(array('web_id' => $shopify_data['web_id']));
            //$siteweb 站点
            !$siteweb && $this->sys_message->wrong('网站不存在!');

            $this->load->library('shopify_api', $siteweb);

            if ($shopify_data['shopify_id'] > 0){
                $response = $this->shopify_api->update_up_goods($shopify_data);
            } else {
                //上传shopify
                $response = $this->shopify_api->upload_goods($shopify_data);
            }

            !$response && $this->sys_message->wrong('上传失败!');

            $shopify_goods_data = array(
                'shopify_id'  => $response['id'],
                'update_time' => 0,
            );
            $this->shopify_goods_model->update_goods($sg_id, $shopify_goods_data);

            $this->sys_message->success('成功!');
        }

        public function cne_order()
        {
            $this->load->library('cne_api');
            $this->load->model('order_model');
            $this->load->library('sys_message');
            $this->load->model('order_goods_model');

            $assoc = $this->uri->uri_to_assoc();

            $order_info = $this->order_model->order_info($assoc['order_id']);

            !$order_info && $this->sys_message->wrong('订单错误！');

            $order_info['order_goods'] = $this->order_goods_model->goods_list($assoc['order_id']);


            $shipping_no = $this->cne_api->PreInputSet($order_info);

            $shipping_no['cMess'] && $this->sys_message->wrong($shipping_no['cMess']);
            $shipping_no['ErrList'][0]['cMess'] && $this->sys_message->wrong($shipping_no['ErrList'][0]['cMess']);

            if ($shipping_no['ErrList']){
                $this->order_model->update_field(array('shipping_no' => $shipping_no['ErrList'][0]['cNo'], 'order_status' => 3), $assoc['order_id']);
            }

            $pdf_url = $order_info['order_sn'] . '-' . ($shipping_no['ErrList'][0]['cNo'] ? $shipping_no['ErrList'][0]['cNo'] : $order_info['shipping_no']) . '.pdf';


            /*$ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $shipping_no['url']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            $file = curl_exec($ch);
            curl_close($ch);
            $filename = pathinfo($shipping_no['url'], PATHINFO_BASENAME);
            $resource = fopen('./shopifydata/'. $pdf_url, 'a');
            fwrite($resource, $file);
            fclose($resource);

            sleep(2);*/

            $this->sys_message->success('成功!', array('url' => $shipping_no['url']));

            //header("Location: {$shipping_no['url']}");

        }

        public function batch_up_goods()
        {
            $this->load->library('sys_message');
            $goods_id = intval($this->input->post('goods_id'));

            $goods = $this->goods_model->goods_info($goods_id);
            !$goods && $this->sys_message->wrong('产品不存在!');


        }

        public function goods_web_up()
        {

            ignore_user_abort();
            set_time_limit(0);

            $this->load->library('sys_message');
            $this->load->model('shopify_goods_model');
            $this->load->model('siteweb_model');
            $this->load->model('goods_model');
            $this->load->library('shopify_api');
            $this->load->model('tagslist_model');

            $goods_id = $this->input->post('goods_id');

            $update_web_id = $this->input->post('web_id');
            if (empty($update_web_id)){
                $this->sys_message->wrong('先选择站点!');
            }

            $goods_sku = $this->db->from('goods_sku')->where(['goods_id' => $goods_id, 'e_update' => 0, 'is_delete' => 0])->get()->result_array();
            if ($goods_sku){
                $this->sys_message->wrong('先上传SKU!');
            }

            $goods = $this->goods_model->goods_info($goods_id, 1);
            !$goods && $this->sys_message->wrong('产品不存在!');

            $siteweb = $this->shopify_goods_model->get_goods_siteweb_list($goods_id);


            foreach ($siteweb as $key => $value) {
                if ( !in_array($value['web_id'], $update_web_id)){
                    unset($siteweb[$key]);
                }
            }

            if (empty($siteweb)){
                $this->sys_message->wrong('商品没有上传过站点');
            }

            //查询商品图片
            $images = array();
            foreach ($goods['images'] AS $row) {
                $images[] = array(
                    'src' => strpos($row['original_img'], 'https://') !== false ? $row['original_img'] : 'http://sumerbikini.com' . $row['original_img'],
                );
            }

            $goods_sku = $this->goods_model->get_goods_sku($goods_id, 1);

            $goods['goods_attr'] = json_decode($goods['goods_attr'], true);

            if ($goods['goods_attr'] && count($goods['goods_attr']['attr_val']) > 1){
                $_attr = array();
                $html  = '<table><tr>';
                foreach ($goods['goods_attr']['attr_title'] as $attr_title) {
                    $html .= '<td>' . $attr_title . '</td>';
                }
                $html .= '</tr>';

                foreach ($goods['goods_attr']['attr_val'] as $k => $_row) {
                    foreach ($_row as $_k => $_row_attr) {
                        $_attr[$_k][$k] = $_row_attr;
                    }
                }

                foreach ($_attr as $k_val => $_attr_val) {
                    $html .= '<tr>';
                    foreach ($_attr_val as $k_title => $attr_title) {
                        if ($k_title == 0){
                            $html .= '<td>' . $attr_title . '</td>';
                        } else {
                            $attr_val = explode('-', $attr_title);

                            $a1   = sprintf('%.1f', $attr_val[0] / 2.54);
                            $a2   = $attr_val[1] ? ("-" . sprintf('%.1f', $attr_val[1] / 2.54)) : '';
                            $html .= '<td>' . $a1 . $a2 . '(' . $attr_title . 'cm)' . '</td>';
                        }
                    }
                    $html .= '</tr>';
                }
                $html .= '</table>';
            }

            $data = array(
                'shop_price'       => $goods['shop_price'],
                'market_price'     => $goods['market_price'],
                'compare_at_price' => $goods['compare_at_price'],
                'body_html'        => $goods['body_html'] . $html,
                'is_sales'         => 1,
                'variants'         => array(),
                'images'           => $images,
            );


            foreach ($siteweb as $key => $_web) {

                $this->shopify_api->initialize($_web);

                $data['shopify_id'] = $_web['shopify_id'];
                $data['web_id']     = $_web['web_id'];
                $data['goods_sn']   = $goods['goods_sn'];
                $data['goods_name'] = "{$_web['title']} " . $goods['goods_name'];

                $variants = array();
                foreach ($goods_sku as $row) {
                    $variants[] = array(
                        'option1' => $row['size'],
                        'option2' => $row['color'],
                        'sku'     => $_web['ab_name'] . $row['sku_num_sn'],
                        'price'   => $goods['shop_price'],
                    );
                }

                $data['variants'] = $variants;
                //查看goods表 shopify_id不存在就是老商品
                if ($_web['shopify_id']){
                    $data['cunzai'] = 1;
                } else {
                    $data['cunzai'] = 0;
                }

                $response = $this->shopify_api->update_up_goods($data);
                //处理shopify图片ID
                foreach ($data['images'] as $key => $value) {
                    //shopify 图片
                    $this->db->where(['album_url' => substr($value['src'], 22)]);
                    $this->db->update('goods_sku', ['img_shopify_id' => $response['images'][$key]['id']]);
                }
                //处理shopify sku ID
                foreach ($data['variants'] as $key => $value) {
                    foreach ($response['variants'] as $k => $v) {
                        if ($v['sku'] == $value['sku']){
                            $this->db->where(['sku_num_sn' => substr($value['sku'], 2)]);
                            $this->db->update('goods_sku', ['sku_shopify_id' => $v['id']]);
                        }
                    }
                }
                //上传SKU图片
                $img_shopify_id = $this->db->from('goods_sku')->where(['goods_id' => $goods_id])->select('img_shopify_id')->group_by('img_shopify_id')->get()->result_array();
                foreach ($img_shopify_id as $key => $value) {
                    if (empty($value['img_shopify_id'])){
                        continue;
                    }

                    $sku_shopify_id = $this->db->from('goods_sku')->where(['img_shopify_id' => $value['img_shopify_id']])->select('sku_shopify_id')->get()->result_array();
                    $variant_ids    = [];

                    foreach ($sku_shopify_id as $k => $v) {
                        $variant_ids[] = $v['sku_shopify_id'];
                    }
                    $res = array('image' => array('id' => $value['img_shopify_id'], 'variant_ids' => $variant_ids));
                    $this->shopify_api->shopify_sku_img($response['id'], $value['img_shopify_id'], $res);
                }
            }
            $this->sys_message->success('成功!');
        }

        public function update_shopify_sku_e()
        {

            $this->load->model('siteweb_model');
            $this->load->model('goods_model');
            $this->load->model('shopify_goods_model');
            $this->load->model('goods_sku_model');
            $this->load->library('sys_message');
            $this->load->library('shopify_api');

            $goods_list = $this->shopify_goods_model->goods_list(array('siteweb_ids' => '17,24,21,26', 'goods_ids' => "5283,3180,3182,3184,3270,3285,3294,3308,3398,3420,3424,3493,3672,3830,3832,3844,3851,3853,3865,3870,3874,3875,3877,3879,3880,3882,3889,3916,3934,3957,3961,3981,4013,4027,4031,4047,4060,4069,4104,4114,4291,4303,4306,4337,4391,4394,4396,4404,4406,4419,4421,4422,4429,4430,4443,4446,4472,4473,4476,4477,4489,4491,4512,4517,4523,4525,4542,4551,4560,4566,4570,4577,4591,4593,4599,4602,4614,4615,4647,4656,4659,4663,4674,4678,4682,4684,4687,4690,4775,4794,4812,4829,4867,4870,4878,4884,4890,4894,4919,4930,4967,4969,4971,4972,4973,4974,4975,4979,4986,5009,5028,5029,5031,5033,5034,5194,5198,5209,5237,5238,5287,5289,5302,5310,5320,5323,5342,5344,5354,5362,5364,5371,5373,5374,5403,5404,5407,5418,5433,5434,5440,5445,5448,5449,5451,5452,5456,5457,5459,5461,5464,5466,5469,5471,5473,5474,5475,5476,5479,5480,5482,5483,5484,5485,5486,5490,5492,5493,5494,5495,5496,5497,5499,5500,5502,5508,5511,5515,5526,5537,4583,1577,1453,1419,1446,1478,1513,1546,1597,1542,1576,1508,1543,1614,1620,1629,1630,1632,1657,1673,1676,1682,1699,1717,1724,1734,1772,1741,1805,1898,1900,1901,1902,1911,1918,1922,1934,1936,1937,1945,1948,1951,1957,1959,1960,1962,1963,1964,1965,1971,1977,1980,1991,1996,1999,2002,2005,2014,2019,2030,2032,2036,2037,2038,2039,2042,2045,2046,2047,2050,2055,2056,2058,2059,2064,2078,2081,2083,2084,2087,2092,2093,2094,2096,2098,2105,2107,2110,2119,2120,2134,2144,2145,2149,2151,2152,2154,2159,2168,2175,2189,2197,2199,2211,2212,2220,2223,2286,2304,2307,2309,2318,2319,2321,2322,2414,2422,2439,2443,2444,2447,2454,2457,2462,2463,2464,2475,2477,2478,2479,2502,2504,2508,2511,2513,2519,2520,2523,2524,2526,2544,2557,2570,2633,2683,2657,2640,2655,2654,2819,2646,2631,2639,2670,2641,2661,2642,2681,2858,3018,2998,2630,2984,2825,2696,2851,2617,2652,2959,2829,2982,2985,3005,1507,1512,1502,1422,1517,3074,3073,1466,3102,3135,1411,3057,3036,3118,3060,3035,3067,3042,3043,3068,3053,3079,3101,3078,3049,3076,1429,1492,1480,1470,1544,1533,1404,1456,1402,1579,1462,1490,1499,1395,5295,5296,5306,5328,5340,5341,5343,5412,5506,3220,5052,5058,5059,5060,5061,5065,5066,5068,5071,5075,5077,5078,5079,5080,5085,5087,5090,5091,5093,5094,5095,5096,5099,5101,5104,5107,5110,5111,5112,5116,5118,5119,5124,5126,5127,5128,5131,5132,5134,5135,5136,5137,5138,5141,5145,5166,5167,5170,5173,5178,5220,5222,5256,5259,5269,5271,5272,5531,3138,3154,3155,3159,3162,3164,3174,3177,3200,3216,3226,3230,3242,3245,3254,3255,3256,3274,3298,3301,3302,3306,3311,3313,3314,3322,3325,3361,3371,3404,3428,3478,3481,3482,3496,3505,3551,3552,3553,3607,3608,3609,3610,3611,3612,3616,3617,3620,3623,3630,3636,3642,3643,3645,3646,3647,3650,3651,3678,3679,3683,3696,3698,3700,3717,3730,3731,3734,3737,3759,3762,3766,3782,3783,3784,3847,3905,3931,3990,3994,3997,4001,4022,4023,4024,4028,4085,4126,4127,4128,4131,4132,4167,4170,4171,4172,4173,4174,4175,4176,4177,4180,4187,4188,4205,4256,4261,4262,4273,4317,4320,4351,4355,4361,4390,4407,4424,4425,4426,4438,4462,4463,4469,4470,4471,4484,4485,4488,4492,4493,4502,4503,4505,4509,4516,4518,4540,4547,4552,4561,4564,4578,4586,4587,4588,4598,4603,4608,4618,4619,4626,4631,4632,4637,4640,4641,4643,4708,4722,4723,4724,4725,4748,4751,4770,4772,4786,4789,4790,4820,4824,4825,4831,4880,4881,4885,4887,4898,4899,4900,4940,4941,4957,4976,4981,4990,4991,4992,4999,5010,5014,5049,3648,5082,5083,5084,5148,5217,5081,5534,5535,5538,5539,5458,5510"), 1);


            print_r($goods_list);

        }

        public function update_shopify_sku()
        {
            ignore_user_abort(true);
            set_time_limit(0);

            $this->load->model('siteweb_model');
            $this->load->model('goods_model');
            $this->load->model('shopify_goods_model');
            $this->load->model('goods_sku_model');
            $this->load->library('sys_message');
            $this->load->library('shopify_api');

            $goods_list = $this->shopify_goods_model->goods_list(array('siteweb_ids' => '17,24,21,26', 'goods_ids' => "5283,3180,3182,3184,3270,3285,3294,3308,3398,3420,3424,3493,3672,3830,3832,3844,3851,3853,3865,3870,3874,3875,3877,3879,3880,3882,3889,3916,3934,3957,3961,3981,4013,4027,4031,4047,4060,4069,4104,4114,4291,4303,4306,4337,4391,4394,4396,4404,4406,4419,4421,4422,4429,4430,4443,4446,4472,4473,4476,4477,4489,4491,4512,4517,4523,4525,4542,4551,4560,4566,4570,4577,4591,4593,4599,4602,4614,4615,4647,4656,4659,4663,4674,4678,4682,4684,4687,4690,4775,4794,4812,4829,4867,4870,4878,4884,4890,4894,4919,4930,4967,4969,4971,4972,4973,4974,4975,4979,4986,5009,5028,5029,5031,5033,5034,5194,5198,5209,5237,5238,5287,5289,5302,5310,5320,5323,5342,5344,5354,5362,5364,5371,5373,5374,5403,5404,5407,5418,5433,5434,5440,5445,5448,5449,5451,5452,5456,5457,5459,5461,5464,5466,5469,5471,5473,5474,5475,5476,5479,5480,5482,5483,5484,5485,5486,5490,5492,5493,5494,5495,5496,5497,5499,5500,5502,5508,5511,5515,5526,5537,4583,1577,1453,1419,1446,1478,1513,1546,1597,1542,1576,1508,1543,1614,1620,1629,1630,1632,1657,1673,1676,1682,1699,1717,1724,1734,1772,1741,1805,1898,1900,1901,1902,1911,1918,1922,1934,1936,1937,1945,1948,1951,1957,1959,1960,1962,1963,1964,1965,1971,1977,1980,1991,1996,1999,2002,2005,2014,2019,2030,2032,2036,2037,2038,2039,2042,2045,2046,2047,2050,2055,2056,2058,2059,2064,2078,2081,2083,2084,2087,2092,2093,2094,2096,2098,2105,2107,2110,2119,2120,2134,2144,2145,2149,2151,2152,2154,2159,2168,2175,2189,2197,2199,2211,2212,2220,2223,2286,2304,2307,2309,2318,2319,2321,2322,2414,2422,2439,2443,2444,2447,2454,2457,2462,2463,2464,2475,2477,2478,2479,2502,2504,2508,2511,2513,2519,2520,2523,2524,2526,2544,2557,2570,2633,2683,2657,2640,2655,2654,2819,2646,2631,2639,2670,2641,2661,2642,2681,2858,3018,2998,2630,2984,2825,2696,2851,2617,2652,2959,2829,2982,2985,3005,1507,1512,1502,1422,1517,3074,3073,1466,3102,3135,1411,3057,3036,3118,3060,3035,3067,3042,3043,3068,3053,3079,3101,3078,3049,3076,1429,1492,1480,1470,1544,1533,1404,1456,1402,1579,1462,1490,1499,1395,5295,5296,5306,5328,5340,5341,5343,5412,5506,3220,5052,5058,5059,5060,5061,5065,5066,5068,5071,5075,5077,5078,5079,5080,5085,5087,5090,5091,5093,5094,5095,5096,5099,5101,5104,5107,5110,5111,5112,5116,5118,5119,5124,5126,5127,5128,5131,5132,5134,5135,5136,5137,5138,5141,5145,5166,5167,5170,5173,5178,5220,5222,5256,5259,5269,5271,5272,5531,3138,3154,3155,3159,3162,3164,3174,3177,3200,3216,3226,3230,3242,3245,3254,3255,3256,3274,3298,3301,3302,3306,3311,3313,3314,3322,3325,3361,3371,3404,3428,3478,3481,3482,3496,3505,3551,3552,3553,3607,3608,3609,3610,3611,3612,3616,3617,3620,3623,3630,3636,3642,3643,3645,3646,3647,3650,3651,3678,3679,3683,3696,3698,3700,3717,3730,3731,3734,3737,3759,3762,3766,3782,3783,3784,3847,3905,3931,3990,3994,3997,4001,4022,4023,4024,4028,4085,4126,4127,4128,4131,4132,4167,4170,4171,4172,4173,4174,4175,4176,4177,4180,4187,4188,4205,4256,4261,4262,4273,4317,4320,4351,4355,4361,4390,4407,4424,4425,4426,4438,4462,4463,4469,4470,4471,4484,4485,4488,4492,4493,4502,4503,4505,4509,4516,4518,4540,4547,4552,4561,4564,4578,4586,4587,4588,4598,4603,4608,4618,4619,4626,4631,4632,4637,4640,4641,4643,4708,4722,4723,4724,4725,4748,4751,4770,4772,4786,4789,4790,4820,4824,4825,4831,4880,4881,4885,4887,4898,4899,4900,4940,4941,4957,4976,4981,4990,4991,4992,4999,5010,5014,5049,3648,5082,5083,5084,5148,5217,5081,5534,5535,5538,5539,5458,5510"), 1);

            $web = $this->siteweb_model->siteweb_list();

            foreach ($goods_list as $item) {
                $this->shopify_api->initialize($web[$item['web_id']]);
                $shopify_sku = $this->shopify_api->get_variants($item['shopify_id']);
                sleep(4);
                if ($shopify_sku['variants']){
                    $data_var = array();
                    foreach ($shopify_sku['variants'] as $val) {
                        $data_var[] = array(
                            'id'    => $val['id'],
                            'price' => $item['g_shop_price'],
                        );


                    }
                    $this->shopify_api->update_variants($item['shopify_id'], $data_var);

                    echo $val['sku'] . '----' . $item['g_shop_price'] . ' --- ' . $val['price'] . ' -- 1<br />';
                    sleep(4);
                } else {
                    print_r($shopify_sku);
                }

            }
        }

        public function ecc_purchase()
        {
            $this->load->library('eccang');
            $this->load->model('suppliers_model');
            $this->load->model('goods_sku_model');
            $this->load->model('custom_purchase_model');
            $this->load->model('epurchase_orders_model');

            $custom_list = $this->custom_purchase_model->custom_list(array(
                                                                         'custom_state' => array(8),
                                                                         'is_down'      => 0,
                                                                     ));

            $_po_codes = array();
            foreach ($custom_list as $item) {
                $_po_codes[$item['custom_id']] = $item['po_code'];
            }

            $pur_orders = $this->eccang->getPurchaseOrders(array(
                                                               'po_codes' => array_filter($_po_codes),
                                                               'pageSize' => 15,
                                                           ));

            $sku_data = array(
                '1606-Red(Top)-S'             => '1606-RedTop-S',
                '1606-White(Top)-S'           => '1606-WhiteTop-S',
                '1606-Red(Top)-M'             => '1606-RedTop-M',
                '1606-White(Top)-M'           => '1606-WhiteTop-M',
                '1606-Red(Top)-L'             => '1606-RedTop-L',
                '1606-White(Top)-L'           => '1606-WhiteTop-L',
                '1606-Red(Top)-XL'            => '1606-RedTop-XL',
                '1606-White(Top)-XL'          => '1606-WhiteTop-XL',
                '1606-Red(Top)-XXL'           => '1606-RedTop-XXL',
                '1606-White(Top)-XXL'         => '1606-WhiteTop-XXL',
                '1612-Pink(Floral)-S'         => '1612-PinkFloral-S',
                '1612-Black(Floral)-S'        => '1612-BlackFloral-S',
                '1612-Stripe(Coffe)-S'        => '1612-StripeCoffe-S',
                '1612-Stripe(Multi)-S'        => '1612-StripeMulti-S',
                '1612-Pink(Floral)-M'         => '1612-PinkFloral-M',
                '1612-Black(Floral)-M'        => '1612-BlackFloral-M',
                '1612-Stripe(Coffe)-M'        => '1612-StripeCoffe-M',
                '1612-Stripe(Multi)-M'        => '1612-StripeMulti-M',
                '1612-Pink(Floral)-L'         => '1612-PinkFloral-L',
                '1612-Black(Floral)-L'        => '1612-BlackFloral-L',
                '1612-Stripe(Coffe)-L'        => '1612-StripeCoffe-L',
                '1612-Stripe(Multi)-L'        => '1612-StripeMulti-L',
                '1612-Pink(Floral)-XL'        => '1612-PinkFloral-XL',
                '1612-Black(Floral)-XL'       => '1612-BlackFloral-XL',
                '1612-Stripe(Coffe)-XL'       => '1612-StripeCoffe-XL',
                '1612-Stripe(Multi)-XL'       => '1612-StripeMulti-XL',
                '1757-Black/Whitestriped-S'   => '1757-BlackWhitestriped-S',
                '1757-Black/Whitestriped-M'   => '1757-BlackWhitestriped-M',
                '1757-Black/Whitestriped-L'   => '1757-BlackWhitestriped-L',
                '1757-Black/Whitestriped-XL'  => '1757-BlackWhitestriped-XL',
                '1757-Black/Whitestriped-XXL' => '1757-BlackWhitestriped-XXL',
                '1758-Black/Whitestriped-S'   => '1758-BlackWhitestriped-S',
                '1758-Black/Whitestriped-M'   => '1758-BlackWhitestriped-M',
                '1758-Black/Whitestriped-L'   => '1758-BlackWhitestriped-L',
                '1758-Black/Whitestriped-XL'  => '1758-BlackWhitestriped-XL',
                '1772-Black/Whitestriped-S'   => '1772-BlackWhitestriped-S',
                '1772-Black/Whitestriped-M'   => '1772-BlackWhitestriped-M',
                '1772-Black/Whitestriped-L'   => '1772-BlackWhitestriped-L',
                '1772-Black/Whitestriped-XL'  => '1772-BlackWhitestriped-XL',
                '1772-Black/Whitestriped-XXL' => '1772-BlackWhitestriped-XXL',
                '1783-Grey/Whitestriped-S'    => '1783-GreyWhitestriped-S',
                '1783-Grey/Whitestriped-M'    => '1783-GreyWhitestriped-M',
                '1783-Grey/Whitestriped-L'    => '1783-GreyWhitestriped-L',
                '1783-Grey/Whitestriped-XL'   => '1783-GreyWhitestriped-XL',
                '1783-Grey/Whitestriped-XXL'  => '1783-GreyWhitestriped-XXL',
                '1835-White/Coffee-OneSize'   => '1835-WhiteCoffee-OneSize',
                '1841-White/Black-M'          => '1841-WhiteBlack-M',
                '1841-White/Black-L'          => '1841-WhiteBlack-L',
                '1841-White/Black-XL'         => '1841-WhiteBlack-XL',
                '1841-White/Black-XXL'        => '1841-WhiteBlack-XXL',
                '1841-Orange/Grey-M'          => '1841-OrangeGrey-M',
                '1841-Orange/Grey-L'          => '1841-OrangeGrey-L',
                '1841-Orange/Grey-XL'         => '1841-OrangeGrey-XL',
                '1841-Orange/Grey-XXL'        => '1841-OrangeGrey-XXL',
                '1855-Green/Pink-Small'       => '1855-GreenPink-Small',
                '1855-Green/Pink-Large'       => '1855-GreenPink-Large',
                '1886-White/Blue-OneSize'     => '1886-WhiteBlue-OneSize',
                '1886-White/Blue-3XL'         => '1886-WhiteBlue-3XL',
                '1805-White/Coffee-US6'       => '1805-WhiteCoffee-US6',
                '2028-Black&WhitePlaid-S'     => '2028-BlackWhitePlaid-S',
                '2028-Black&WhitePlaid-M'     => '2028-BlackWhitePlaid-M',
                '2028-Black&WhitePlaid-L'     => '2028-BlackWhitePlaid-L',
                '2028-Black&WhitePlaid-XL'    => '2028-BlackWhitePlaid-XL',
                '2092-Grey/Whitestriped-S'    => '2092-GreyWhitestriped-S',
                '2092-Grey/Whitestriped-M'    => '2092-GreyWhitestriped-M',
                '2092-Grey/Whitestriped-L'    => '2092-GreyWhitestriped-L',
                '2092-Grey/Whitestriped-XL'   => '2092-GreyWhitestriped-XL',
                '2092-Black/CoffeeStriped-S'  => '2092-BlackCoffeeStriped-S',
                '2092-Black/CoffeeStriped-M'  => '2092-BlackCoffeeStriped-M',
                '2092-Black/CoffeeStriped-L'  => '2092-BlackCoffeeStriped-L',
                '2092-Black/CoffeeStriped-XL' => '2092-BlackCoffeeStriped-XL',
                '2092-Black/Whitestriped-S'   => '2092-BlackWhitestriped-S',
                '2092-Black/Whitestriped-M'   => '2092-BlackWhitestriped-M',
                '2092-Black/Whitestriped-L'   => '2092-BlackWhitestriped-L',
                '2092-Black/Whitestriped-XL'  => '2092-BlackWhitestriped-XL',
                '2120-Black/Whitestriped-S'   => '2120-BlackWhitestriped-S',
                '2120-Black/Whitestriped-M'   => '2120-BlackWhitestriped-M',
                '2120-Black/Whitestriped-L'   => '2120-BlackWhitestriped-L',
                '2120-Black/Whitestriped-XL'  => '2120-BlackWhitestriped-XL',
                '2120-Black/Whitestriped-XXL' => '2120-BlackWhitestriped-XXL',
                '2126-Black/Whitestriped-S'   => '2126-BlackWhitestriped-S',
                '2126-Black/Whitestriped-M'   => '2126-BlackWhitestriped-M',
                '2126-Black/Whitestriped-L'   => '2126-BlackWhitestriped-L',
                '2126-Black/Whitestriped-XL'  => '2126-BlackWhitestriped-XL',
                '2155-Black/Whitestriped-S'   => '2155-BlackWhitestriped-S',
                '2155-Black/Whitestriped-M'   => '2155-BlackWhitestriped-M',
                '2155-Black/Whitestriped-L'   => '2155-BlackWhitestriped-L',
                '2155-Black/Whitestriped-XL'  => '2155-BlackWhitestriped-XL',
                '2158-Black/Whitestriped-S'   => '2158-BlackWhitestriped-S',
                '2158-Black/Whitestriped-M'   => '2158-BlackWhitestriped-M',
                '2158-Black/Whitestriped-L'   => '2158-BlackWhitestriped-L',
                '2158-Black/Whitestriped-XL'  => '2158-BlackWhitestriped-XL',
                '2235-Orange/Grey-S'          => '2235-OrangeGrey-S',
                '2235-Orange/Grey-M'          => '2235-OrangeGrey-M',
                '2235-Orange/Grey-L'          => '2235-OrangeGrey-L',
                '2235-Orange/Grey-XL'         => '2235-OrangeGrey-XL',
                '2235-Orange/Grey-XXL'        => '2235-OrangeGrey-XXL',
                '2346-White/Black-S'          => '2346-WhiteBlack-S',
                '2346-White/Black-M'          => '2346-WhiteBlack-M',
                '2346-White/Black-L'          => '2346-WhiteBlack-L',
                '2346-White/Black-XL'         => '2346-WhiteBlack-XL',
                '2537-Black/Whitestriped-S'   => '2537-BlackWhitestriped-S',
                '2537-Black/Whitestriped-M'   => '2537-BlackWhitestriped-M',
                '2537-Black/Whitestriped-L'   => '2537-BlackWhitestriped-L',
                '2537-Black/Whitestriped-XL'  => '2537-BlackWhitestriped-XL',
                '2674-Black&WhitePlaid-S'     => '2674-BlackWhitePlaid-S',
                '2674-Black&WhitePlaid-M'     => '2674-BlackWhitePlaid-M',
                '2674-Black&WhitePlaid-L'     => '2674-BlackWhitePlaid-L',
                '2674-Black&WhitePlaid-XL'    => '2674-BlackWhitePlaid-XL',
                '2828-Black&WhitePlaid-S'     => '2828-BlackWhitePlaid-S',
                '2828-Black&WhitePlaid-M'     => '2828-BlackWhitePlaid-M',
                '2828-Black&WhitePlaid-L'     => '2828-BlackWhitePlaid-L',
                '2828-Black&WhitePlaid-XL'    => '2828-BlackWhitePlaid-XL',
                '2836-Black/Whitestriped-S'   => '2836-BlackWhitestriped-S',
                '2836-Black/Whitestriped-M'   => '2836-BlackWhitestriped-M',
                '2836-Black/Whitestriped-L'   => '2836-BlackWhitestriped-L',
                '2836-Black/Whitestriped-XL'  => '2836-BlackWhitestriped-XL',
                '2951-Royalblue&white-S'      => '2951-Royalbluewhite-S',
                '2951-Royalblue&white-M'      => '2951-Royalbluewhite-M',
                '2951-Royalblue&white-L'      => '2951-Royalbluewhite-L',
                '2951-Royalblue&white-XL'     => '2951-Royalbluewhite-XL',
                '2951-Royalblue&white-S'      => '2951-Royalbluewhite-S',
                '2951-Royalblue&white-M'      => '2951-Royalbluewhite-M',
                '2951-Royalblue&white-L'      => '2951-Royalbluewhite-L',
                '2951-Royalblue&white-XL'     => '2951-Royalbluewhite-XL',
                '3086-Black/Whitestriped-S'   => '3086-BlackWhitestriped-S',
                '3086-Black/Whitestriped-M'   => '3086-BlackWhitestriped-M',
                '3086-Black/Whitestriped-L'   => '3086-BlackWhitestriped-L',
                '3086-Black/Whitestriped-XL'  => '3086-BlackWhitestriped-XL',
            );

            $_data       = array();
            $_data_goods = array();
            foreach ($pur_orders['data'] as $data) {

                $pu_order = $this->epurchase_orders_model->info(array('po_id', $data['po_id']));
                if ($pu_order){
                    continue;
                }

                $supplier = $this->suppliers_model->suppliers_info(array(
                                                                       'e_code' => $data['supplier_code'],
                                                                   ));

                $_data[] = array(
                    'po_id'              => $data['po_id'],
                    'po_code'            => $data['po_code'],
                    'tracking_no'        => $data['tracking_no'],
                    'ref_no'             => $data['ref_no'],
                    'payable_amount'     => $data['payable_amount'],
                    'actually_amount'    => $data['actually_amount'],
                    'currency_code'      => trim($data['currency_code']),
                    'pay_status'         => intval($data['pay_status']),
                    'po_staus'           => intval($data['po_staus']),
                    'date_create'        => strtotime($data['date_create']),
                    'date_eta'           => strtotime($data['date_eta']),
                    'date_release'       => strtotime($data['date_release']),
                    'po_completion_time' => strtotime($data['po_completion_time']),
                    'return_verify'      => urldecode($data['return_verify']),
                    'pay_ship_amount'    => floatval($data['pay_ship_amount']),
                    'create_type'        => intval($data['create_type']),
                    'pts_status_sort'    => $data['pts_status_sort'],
                    'account_type'       => intval($data['account_type']),
                    'transaction_no'     => $data['transaction_no'],
                    'supplier_id'        => $supplier['suppliers_id'],
                    'verify'             => $data['verify'],
                    'qty_expected_all'   => $data['qty_expected_all'],
                    'qty_receving_all'   => $data['qty_receving_all'],
                    'po_is_net'          => $data['po_is_net'],
                    'purchase_json'      => json_encode($data),
                );

                foreach ($data['detail'] as $detail) {
                    $goods_sku     = $this->goods_sku_model->sku_info(array(
                                                                          'sku_sn' => $sku_data[$detail['product_sku']] ? $sku_data[$detail['product_sku']] : $detail['product_sku'],
                                                                      ));
                    $_data_goods[] = array(
                        'po_id'              => $data['po_id'],
                        'goods_id'           => $goods_sku['goods_id'],
                        'sku_id'             => $goods_sku['sku_id'],
                        'qty_expected'       => $detail['qty_expected'],
                        'qty_pay'            => $detail['qty_pay'],
                        'qty_eta'            => $detail['qty_eta'],
                        'qty_receving'       => $detail['qty_receving'],
                        'qty_free'           => $detail['qty_free'],
                        'unit_price'         => floatval($detail['unit_price']),
                        'total_price'        => floatval($detail['total_price']),
                        'currency_code'      => trim($detail['currency_code']),
                        'product_sku'        => $detail['product_sku'],
                        'first_receive_time' => strtotime($detail['first_receive_time']),
                    );
                }

            }

            if ($_data){
                $this->epurchase_orders_model->insert_batch($_data);
                $this->epurchase_orders_model->goods_insert_batch($_data_goods);
            }
        }

        public function e_daily_select()
        {
            $this->load->library('eccang');
            $data['pageSize']       = 1000;
            $data['page']           = 1;
            $data['searchDateType'] = 'createDate';
            $data['dateFor']        = date("Y-m-d", strtotime("-1 day"));
            $data['dateTo']         = date("Y-m-d");
            $res                    = $this->eccang->same_list_sku($data);
            if ( !empty($res['data'])){
                foreach ($res['data'] as $k => $v) {
                    $v['track']              = json_encode($v['track']);
                    $v['single_net_number']  = json_encode($v['single_net_number']);
                    $v['detail']             = json_encode($v['detail']);
                    $v['date_create']        = strtotime($v['date_create']);
                    $v['date_release']       = strtotime($v['date_release']);
                    $v['po_completion_time'] = strtotime($v['po_completion_time']);
                    $this->db->insert('purchase_order_e', $v);
                    $id = $this->db->insert_id();
                    foreach (json_decode($v['detail'], true) as $key => $val) {
                        $val['po_id']              = $id;
                        $val['first_receive_time'] = strtotime($val['first_receive_time']);
                        $this->db->insert('purchase_goods_e', $val);
                    }
                }
            }
        }

        public function goods_delete()
        {
            $this->load->model('siteweb_model');
            $siteweb = $this->siteweb_model->siteweb_info(array('web_name' => 'weststylish'));
            $this->load->library('shopify_api', $siteweb);
            $sn       = $this->input->get('sn');
            $sn       = explode(',', $sn);
            $goods_id = $this->db->from('goods')->select('goods_id')->where_in('goods_sn', $sn)->get()->result_array();
            foreach ($goods_id as $key => $value) {
                $shopify_id = $this->db->from('shopify_goods')
                                       ->select('shopify_id')
                                       ->where(['goods_id' => $value['goods_id'], 'web_id' => 26])
                                       ->get()->row_array();
                $arr        = $this->shopify_api->goods_delete($shopify_id['shopify_id']);
                $this->db->set('is_sales', 0);
                $this->db->where(['goods_id' => $value['goods_id'], 'web_id' => 26]);
                $this->db->update('shopify_goods');
            }

        }

        public function goods_up_web_all()
        {
            // $this->db->where(['id'=>21]);
            // $this->db->update('goods_upload',['is_upload'=>0]);
            // echo 1;die;
            $this->load->library('sys_message');
            $this->load->model('shopify_goods_model');
            $this->load->model('siteweb_model');
            $this->load->model('goods_model');
            $this->load->library('shopify_api');
            $this->load->model('tagslist_model');

            $res = $this->db->from('goods_upload')->where(['is_upload' => 0])->limit(5)->get()->result_array();
            if (empty($res)){
                return false;
            }
            foreach ($res as $k => $v) {
                sleep(3);
                $goods = $this->goods_model->goods_info($v['goods_id']);


                $siteweb = $this->db->from('siteweb as s')
                                    ->select('s.*,sg.sg_id,sg.shopify_id, sg.is_sales')
                                    ->join('shopify_goods as sg', 's.web_id = sg.web_id', 'left')
                                    ->where(['sg.goods_id' => $v['goods_id'], 's.web_id' => $v['web_id']])
                                    ->get()->row_array();

                // print_R($goods['goods_id']);die;

                $images_query    = $this->db->from('goods_album')->where(['goods_id' => $goods['goods_id'], 'is_delete' => 0])->get();
                $goods['images'] = array();
                foreach ($images_query->result_array() AS $row) {
                    if (strpos($row['original_img'], 'https://') !== false){
                        $goods['images'][] = array(
                            'src' => $row['original_img'],
                        );
                    } else {
                        $goods['images'][] = array(
                            'attachment' => $this->shopify_goods_model->imgToBase64($row['original_img']),
                        );
                    }

                }

                $goods_sku           = $this->goods_model->get_goods_sku($goods['goods_id'], 1);
                $goods['goods_attr'] = json_decode($goods['goods_attr'], true);

                if ($goods['goods_attr'] && count($goods['goods_attr']['attr_val']) > 1){
                    $_attr = array();
                    $html  = '<table><tr>';
                    foreach ($goods['goods_attr']['attr_title'] as $attr_title) {
                        $html .= '<td>' . $attr_title . '</td>';
                    }
                    $html .= '</tr>';

                    foreach ($goods['goods_attr']['attr_val'] as $k => $_row) {
                        foreach ($_row as $_k => $_row_attr) {
                            $_attr[$_k][$k] = $_row_attr;
                        }
                    }

                    foreach ($_attr as $k_val => $_attr_val) {
                        $html .= '<tr>';
                        foreach ($_attr_val as $k_title => $attr_title) {
                            if ($k_title == 0){
                                $html .= '<td>' . $attr_title . '</td>';
                            } else {
                                $attr_val = explode('-', $attr_title);

                                $a1   = sprintf('%.1f', $attr_val[0] / 2.54);
                                $a2   = $attr_val[1] ? ("-" . sprintf('%.1f', $attr_val[1] / 2.54)) : '';
                                $html .= '<td>' . $a1 . $a2 . '(' . $attr_title . 'cm)' . '</td>';
                            }
                        }
                        $html .= '</tr>';
                    }
                    $html .= '</table>';
                }
                $data = array(
                    'goods_id'     => $goods['goods_id'],
                    'goods_sn'     => $siteweb['ab_name'] . $goods['goods_sn'],
                    'web_id'       => 0,
                    'goods_name'   => $goods['goods_name'],
                    'cat_id'       => $goods['cat_id'],
                    'shop_price'   => $goods['shop_price'],
                    'market_price' => $goods['market_price'],
                    'body_html'    => $goods['body_html'] . $html,
                    'is_sales'     => 1,
                    'variants'     => array(),
                    'images'       => $goods['images'],
                    'tags' => $this->tagslist_model->tags_in($goods['goods_id'])
                );
                if ($this->tagslist_model->tags_in($goods['tags'])){
                    $data = array(
                        'tags' => $this->tagslist_model->tags_in($goods['tags']),
                    );
                }

                $this->shopify_api->initialize($siteweb);

                $data['shopify_id'] = $siteweb['shopify_id'];
                $data['web_id']     = $siteweb['web_id'];
                $data['goods_sn']   = $siteweb['ab_name'] . $goods['goods_sn'];
                $data['goods_name'] = "{$siteweb['title']} " . $goods['goods_name'];

                $variants = array();
                foreach ($goods_sku as $row) {
                    $variants[] = array(
                        'option1' => $row['size'],
                        'option2' => $row['color'],
                        'sku'     => $siteweb['ab_name'] . $row['sku_num_sn'],
                        'price'   => $goods['shop_price'],
                    );
                }
                // print_R($variants);die;
                $data['variants'] = $variants;
                $res              = $this->db->from('goods')->where(['shopify_id' => $data['shopify_id']])->get();
                if ($res->result_array()){
                    $data['cunzai'] = 1;
                } else {
                    $data['cunzai'] = 0;
                }
                // print_R($data);die;
                $response = $this->shopify_api->update_up_goods($data);
                // $this->shopify_goods_model->insert_goods($data,$_web['sg_id']);
                $this->db->where(['id' => $v['id']])->update('goods_upload', ['is_upload' => 1]);
            }
        }

        public function shopify_user_add()
        {
            $created_at_min = date('Y-m-d', time() - 3600 * 24) . 'T00:00:00-04:00';
            $created_at_max = date('Y-m-d', time()) . 'T00:00:00-04:00';
            $web_info       = $this->db->from('siteweb')->get()->result_array();
            $this->load->library('shopify_api');
            foreach ($web_info as $k => $v) {
                $this->shopify_api->initialize($v);
                $res = $this->shopify_api->shopify_user_add($created_at_min, $created_at_max);
                if ( !empty($res['customers'])){
                    foreach ($res['customers'] as $key => $val) {
                        $array['email']       = $val['email'];
                        $array['first_name']  = (string)$val['first_name'];
                        $array['last_name']   = (string)$val['last_name'];
                        $array['web_user_id'] = $val['id'];
                        $array['add_time']    = time();
                        $array['web_id']      = $v['web_id'];
                        $this->db->insert('customer', $array);
                    }
                }
            }


        }
        //查询E仓订单数据
        //逻辑：查询e_page分页表抓取E仓如果够50条（添加订单，添加订单商品，添加地址）修改e_page分页+1
        public function e_roder()
        {
            $this->load->library('eccang');
            $page               = $this->db->from('e_page')->where(['id' => 1])->select('e_order_page')->get()->row_array();
            $data['page']       = (int)$page['e_order_page'];
            $data['getDetail']  = 1;
            $data['getAddress'] = 1;
            $res                = $this->eccang->order_handle($data);
            // print_R($res);die;
            if ( !count($res['data']) == 50){
                return false;
            }
            foreach ($res['data'] as $k => $v) {
                $v['createdDate']           = strtotime($v['createdDate']);
                $v['updateDate']            = strtotime($v['updateDate']);
                $v['datePaidPlatform']      = strtotime($v['datePaidPlatform']);
                $v['platformShipTime']      = strtotime($v['platformShipTime']);
                $v['dateWarehouseShipping'] = strtotime($v['dateWarehouseShipping']);
                $orderDetails               = $v['orderDetails'];
                $orderAddress               = $v['orderAddress'];
                unset($v['orderConfigDatas']);
                unset($v['orderDetails']);
                unset($v['orderAddress']);
                //添加订单
                $this->db->insert('e_order', $v);
                $order_id = $this->db->insert_id();
                //添加订单的商品
                foreach ($orderDetails as $key => $val) {
                    $sku = $this->db->from('goods_sku')
                                    ->where(['sku_num_sn' => substr($val['productSku'], 2)])
                                    ->select('goods_id,sku_id')
                                    ->get()->row_array();
                    if (empty($sku)){
                        $sku['goods_id'] = 0;
                        $sku['sku_id']   = 0;
                    }
                    $val['goods_id']     = $sku['goods_id'];
                    $val['goods_sku_id'] = $sku['sku_id'];
                    $val['operTime']     = strtotime($val['operTime']);
                    unset($val['saleOrderCode']);
                    unset($val['saleOrderCodeOrg']);
                    $val['order_id'] = $order_id;
                    $this->db->insert('e_orderdetails', $val);
                }
                //添加地址
                $orderAddress['order_id']    = $order_id;
                $orderAddress['createdDate'] = strtotime($v['createdDate']);
                $orderAddress['updateDate']  = strtotime($v['updateDate']);
                $this->db->insert('e_orderaddress', $orderAddress);
            }
            $this->db->where(['id' => 1]);
            $this->db->update('e_page', ['e_order_page' => $page['e_order_page'] + 1]);
        }
        //E仓退款订单
        //逻辑：查询e_page分页表抓取E仓如果够15条（添加订单，添加订单商品，添加地址）修改e_page分页+1
        public function order_handle_refund()
        {
            $this->load->library('eccang');
            $page                  = $this->db->from('e_page')->where(['id' => 2])->select('e_order_page')->get()->row_array();
            $data['ex_rma_status'] = 3;
            $data['page']          = (int)$page['e_order_page'];
            $res                   = $this->eccang->order_handle_refund($data);
            // print_r($res);die;
            if ( !count($res['data']) == 15){
                return false;
            }
            foreach ($res['data'] as $k => $v) {
                $v['create_date']         = strtotime($v['create_date']);
                $v['verify_date']         = strtotime($v['verify_date']);
                $v['paid_date']           = strtotime($v['paid_date']);
                $v['warehouse_ship_date'] = strtotime($v['warehouse_ship_date']);
                $v['refund_date']         = strtotime($v['refund_date']);
                //订单表ID
                $order_id        = $this->db->from('e_order')
                                            ->where(['saleOrderCode' => $v['rma_refrence_no_platform']])
                                            ->select('id')->get()->row_array();
                $v['e_order_id'] = $order_id['id'];
                //订单商品ID
                $goods_id               = substr($v['product_sku'], 0, strpos($v['product_sku'], '-'));
                $e_orderdetails_id      = $this->db->from('e_orderdetails')
                                                   ->where(['order_id' => $order_id['id'], 'goods_id' => $goods_id])
                                                   ->select('id')->get()->row_array();
                $v['e_orderdetails_id'] = $e_orderdetails_id['id'];
                if ($v['refund_type'] == '全款'){
                    $v['refund_type'] = 1;
                } elseif ($v['refund_type'] == '部分') {
                    $v['refund_type'] = 2;
                } else {
                    $v['refund_type'] = 0;
                }
                $v['status']      = 3;
                $v['refund_step'] = 0;
                switch ($v['reason']) {
                    case "尺码偏大":
                        $v['reason'] = 1;
                        break;
                    case "尺码偏小":
                        $v['reason'] = 2;
                        break;
                    case "面料问题":
                        $v['reason'] = 3;
                        break;
                    case "色差问题":
                        $v['reason'] = 4;
                        break;
                    case "产品破损":
                        $v['reason'] = 5;
                        break;
                    case "脏污问题":
                        $v['reason'] = 6;
                        break;
                    case "产品印花":
                        $v['reason'] = 7;
                        break;
                    case "产品版型":
                        $v['reason'] = 8;
                        break;
                    case "误拍":
                        $v['reason'] = 9;
                        break;
                    case "爆款耽误":
                        $v['reason'] = 10;
                        break;
                    case "断货下架":
                        $v['reason'] = 11;
                        break;
                    case "退运费":
                        $v['reason'] = 12;
                        break;
                    case "断货换货":
                        $v['reason'] = 13;
                        break;
                    case "退优惠券金额":
                        $v['reason'] = 14;
                        break;
                    default:
                        $v['reason'] = 0;
                }
                $this->db->insert('e_orderrefund', $v);
            }
            $this->db->where(['id' => 2]);
            $this->db->update('e_page', ['e_order_page' => $page['e_order_page'] + 1]);
        }

        //上传商品SKU到E仓
        public function e_goods_sku()
        {
            $array = $this->db->from('goods_sku')->where('goods_id != 0')->where(['e_update' => 0, 'is_delete' => 0])->limit(20)->get()->result_array();
            if (empty($array)){
                return false;
            }
            foreach ($array as $k => $v) {
                $goods          = $this->db->from('goods')
                                           ->where(['goods_id' => $v['goods_id']])
                                           ->select('cn_name,goods_name,type_id,in_price,goods_weight,suppliers_id,shop_price,supp_url')
                                           ->get()->row_array();
                $type           = $this->db->from('goods_type')
                                           ->where(['cat_id' => $goods['type_id']])
                                           ->select('cat_name_zh,cat_name,cate_code')
                                           ->get()->row_array();
                $suppliers_name = $this->db->from('suppliers')
                                           ->where(['suppliers_id' => $goods['suppliers_id']])
                                           ->select('suppliers_name,suppliers_id')
                                           ->get()->row_array();
                $goods_album    = $this->db->from('goods_album')
                                           ->where(['goods_id' => $v['goods_id'], 'is_delete' => 0])
                                           ->select('original_img')
                                           ->get()->result_array();
                $album          = [];
                foreach ($goods_album as $key => $val) {
                    $album[] = 'http://sumerbikini.com' . $val['original_img'];
                }
                $this->load->library('eccang');
                $info = $this->eccang->getSupplierInfo(['condition' => ['supplierName' => trim($suppliers_name['suppliers_name'])]]);
                if ( !empty($info['data'])){
                    $defaultSupplierCode = $info['data'][0]['supplierCode'];
                } else {
                    $defaultSupplierCode = 'G' . $suppliers_name['suppliers_id'];
                    $data                = [
                        'actionType' => 'ADD',
                        'supplier'   => [
                            'supplierCode'         => $defaultSupplierCode,
                            'supplierName'         => $suppliers_name['suppliers_name'],
                            'buyerId'              => $suppliers_name['suppliers_id'] % 2 == 1 ? 583 : 609,
                            'level'                => 'A',
                            'supplierTeamworkType' => 0,
                            'supplierType'         => 1,
                            'pcId'                 => 3,
                            'accountType'          => 2,
                            'payType'              => 1,
                            'supplierCarrier'      => 1,
                            'shippingMethodIdHead' => 2,
                            'supplierQcException'  => 2,
                            'accountProportion'    => 100,
                        ],
                    ];
                    $suppliers_e         = $this->eccang->syncSupplierInfo($data);
                    $this->db->where(['suppliers_id' => $suppliers_name['suppliers_id']]);
                    $this->db->update('suppliers', ['e_code' => $suppliers_e['data']['supplierCode']]);
                }

                $colors                            = $this->db->from('colors')->where(['color_en' => $v['color']])->select('e_id')->get()->row_array();
                $size                              = $this->db->from('size')->where(['size_value' => $v['size']])->select('e_id')->get()->row_array();
                $ali_color                         = !empty($v['ali_color']) ? $v['ali_color'] : $v['color'];
                $ali_size                          = !empty($v['ali_size']) ? $v['ali_size'] : $v['size'];
                $res                               = [];
                $res['actionType']                 = 'ADD';
                $res['productSku']                 = $v['sku_sn'];
                $res['productTitle']               = $goods['cn_name'] . '---' . $ali_color . '/' . $ali_size;
                $res['productTitleEn']             = $goods['goods_name'];
                $res['pdOverseaTypeCn']            = $type['cat_name_zh'];
                $res['pdOverseaTypeEn']            = $type['cat_name'];
                $res['productDeclaredValue']       = 1.5;
                $res['pdDeclareCurrencyCode']      = 'USD';
                $res['productPurchaseValue']       = (Float)$goods['in_price'];
                $res['productPurchaseValueNotTax'] = (Float)$goods['in_price'];
                $res['currencyCode']               = 'RMB';
                $res['productWeight']              = $goods['goods_weight'] < 50 ? 0.05 : $goods['goods_weight'] / 1000;
                $res['defaultSupplierCode']        = $defaultSupplierCode;
                $res['productPrice']               = $goods['shop_price'];
                $res['oprationType']               = 2;
                $res['productStatus']              = 1;
                $res['saleStatus']                 = 2;
                $res['hsCode']                     = $type['cate_code'];
                $res['productLength']              = 1;
                $res['productWidth']               = 1;
                $res['productHeight']              = 1;
                $res['productColorId']             = $colors['e_id'];
                $res['productSizeId']              = $size['e_id'];
                $res['spMinQty']                   = 1;
                $res['spProductAddress']           = $goods['supp_url'];
                $res['productImgUrlList']          = $album;
                $info                              = $this->eccang->add_syncProduct($res);
                if ($info['code'] == 200 || $info['error'][0]['errorCode'] == '10001'){
                    $this->db->where(['sku_id' => $v['sku_id']]);
                    $this->db->update('goods_sku', ['e_update' => 1]);
                }
            }
        }

        //映射E仓sku和shopify站点sku
        public function modifySkuRelation()
        {
            $this->load->library('eccang');
            $arr = $this->db->from('shopify_goods')
                            ->limit(5)
                            ->where(['shopify_e_sku_mapping' => 0])
                            ->select('web_id,goods_id,sg_id')
                            ->get()->result_array();
            if (empty($arr)){
                return false;
            }
            foreach ($arr as $key => $val) {
                $data    = array();
                $ab_name = $this->db->from('siteweb')->where(['web_id' => $val['web_id']])->select('ab_name')->get()->row_array();
                $sku_sn  = $this->db->from('goods_sku')->select('sku_sn,sku_num_sn')->where(['goods_id' => $val['goods_id']])->get()->result_array();
                foreach ($sku_sn as $keys => $value) {
                    $data['data'][] = array(
                        'product_sku' => $ab_name['ab_name'] . $value['sku_num_sn'],
                        'pcr'         => array(
                            array(
                                'pcr_product_sku' => $value['sku_sn'],
                                'pcr_quantity'    => 1,
                            ),
                        ),
                    );
                }
                $this->db->where(['sg_id' => $val['sg_id']]);
                $this->db->update('shopify_goods', ['shopify_e_sku_mapping' => 1]);
                $this->eccang->modifySkuRelation($data);
            }

        }

        public function aa()
        {
            $data = Array(
                'data' => Array(
                    Array(
                        'product_sku' => 'QS16193406404',
                        'pcr'         => Array(
                            Array(
                                'pcr_product_sku' => '2453-BLACKGREY-XL',
                                'pcr_quantity'    => 1,
                            ),
                        ),
                    ),
                ),
            );
            $this->load->library('eccang');
            $this->eccang->modifySkuRelation($data);
        }

        public function baby_goods_update(){
            $baby_update = $this->db->from('baby_update')->where(['is_up'=>0])->limit(3)->get()->result_array();
            foreach ($baby_update as $baby_update_k => $baby_update_v) {
                
            
            $this->load->library('sys_message');
            $this->load->model('siteweb_model');
            $this->load->library('shopify_api');
            $baby_goods = $this->db->from('baby_goods')->where(['id'=>$baby_update_v['baby_goods_id']])->get()->row_array();

            $goods_sku = $this->db->from('baby_goods_sku')->where(['baby_goods_id' => $baby_update_v['baby_goods_id'], 'baby_is_delete' => 0])->get()->result_array();
            // if(!$goods_sku){
            //     $this->sys_message->wrong('先上传SKU!');
            // }
            // if (empty($web_id)){
            //     $this->sys_message->wrong('请选择站点!');
            // }

            foreach ($goods_sku as $key => $value) {
                $size_value = $this->db->from('size')->where(['size_id'=>$value['baby_sku_size']])->select('size_value')->get()->row_array();
                $color_en = $this->db->from('colors')->where(['color_id'=>$value['baby_sku_head']])->select('color_en')->get()->row_array();
                $sku[$key]['option1'] = $size_value['size_value'];
                $sku[$key]['option2'] = $color_en['color_en'];
                $sku[$key]['sku']     = $value['baby_goods_sku'];
                $sku[$key]['price']   = $baby_goods['baby_goods_price'];
            }
            $color['name'] = 'size';
            foreach ($goods_sku as $k => $v) {
                $color_en = $this->db->from('colors')->where(['color_id'=>$v['baby_sku_head']])->select('color_en')->get()->row_array();
                $color['values'][] = $color_en['color_en'];
            }
            $size['name'] = 'color';
            foreach ($goods_sku as $k => $v) {
                $size_value = $this->db->from('size')->where(['size_id'=>$v['baby_sku_size']])->select('size_value')->get()->row_array();
                $size['values'][] = $size_value['size_value'];
            }
            $options = [];
            $options[] = $color;
            $options[] = $size;
            $baby_goods_img = $this->db->from('baby_goods_img')->where(['baby_goods_id'=>$baby_update_v['baby_goods_id'],'baby_is_delete'=>0])->get()->result_array();
            $img = [];
            foreach ($baby_goods_img as $key => $value) {
                $img[]['src'] = 'http://sumerbikini.com/'.$value['baby_goods_img'];
            }
            // foreach ($web_id as $web_key => $web_val) {
                $baby_shopify_goods = $this->db->from('baby_shopify_goods')->where(['web_id'=>$baby_update_v['web_id'],'baby_goods_id'=>$baby_update_v['baby_goods_id']])->get()->row_array();
                if($baby_shopify_goods){
                    $this->db->where(['id'=>$baby_update_v['id']]);
                    $this->db->update('baby_update',['is_up'=>1]);
                    continue;
                }
                $val['baby_goods_id'] = $baby_update_v['baby_goods_id'];
                $val['web_id'] = $baby_update_v['web_id'];
                $val['goods_name'] = $baby_goods['baby_goods_name'];
                $val['goods_sn'] = $baby_goods['baby_goods_sn'];
                $val['goods_price'] = $baby_goods['baby_goods_price'];
                $val['variants'] = json_encode($sku);
                $val['add_time'] = time();
                $this->db->insert('baby_shopify_goods',$val);
                $id = $this->db->insert_id();
                $siteweb = $this->siteweb_model->siteweb_info(array('web_id' => $baby_update_v['web_id']));
                $this->shopify_api->initialize($siteweb);

                $baby_goods['goods_attr'] = json_decode($baby_goods['goods_attr'], true);
                if ($baby_goods['goods_attr'] && count($baby_goods['goods_attr']['attr_val']) > 1){
                    $html = '<table><tr>';
                    foreach ($baby_goods['goods_attr']['attr_title'] as $attr_title) {
                        $html .= '<td>' . $attr_title . '</td>';
                    }
                    $html .= '</tr>';

                    $_attr = array();
                    foreach ($baby_goods['goods_attr']['attr_val'] as $k => $_row) {
                        foreach ($_row as $_k => $_row_attr) {
                            $_attr[$_k][$k] = $_row_attr;
                        }
                    }

                    foreach ($_attr as $k_val => $_attr_val) {
                        $html .= '<tr>';
                        foreach ($_attr_val as $k_title => $attr_title) {
                            if ($k_title == 0){
                                $html .= '<td>' . $attr_title . '</td>';
                            } else {
                                $attr_val = explode('-', $attr_title);

                                $a1   = sprintf('%.1f', $attr_val[0] / 2.54);
                                $a2   = $attr_val[1] ? ("-" . sprintf('%.1f', $attr_val[1] / 2.54)) : '';
                                $html .= '<td>' . $a1 . $a2 . '(' . $attr_title . 'cm)' . '</td>';
                            }
                        }
                        $html .= '</tr>';
                    }
                    $html .= '</table>';
                }
                $baby_goods['baby_goods_describe'] .= $html;
// if($baby_update_k == 1){
//                     print_R($baby_goods);die;
//                 }
// print_R($baby_goods);die;
                $baby_shopify_data['baby_goods_name'] = $baby_goods['baby_goods_name'];
                $baby_shopify_data['baby_body_html'] = $baby_goods['baby_goods_describe'];
                $baby_shopify_data['variants'] = $sku;
                $baby_shopify_data['images'] = $img;
                $baby_shopify_data['options'] = $options;
                // if($baby_update_k == 1){
                    // print_R($baby_shopify_data);die;
                // }
                $info = $this->shopify_api->baby_upload_goods($baby_shopify_data);
                // if($baby_update_k == 1){
                //     print_R($info);die;
                // }
                foreach ($info['variants'] as $key => $value) {
                    $baby_sku_img = $this->db->from('baby_goods_sku')->where(['baby_goods_sku'=>$value['sku']])->select('baby_sku_img')->get()->row_array();
                    foreach ($baby_goods_img as $k => $v) {
                        if($v['baby_goods_img'] == $baby_sku_img['baby_sku_img']){
                            $this->db->where(['baby_goods_sku'=>$value['sku']]);
                            $this->db->update('baby_goods_sku',['baby_shopify_img_id'=>$info['images'][$k]['id'],'baby_shopify_sku_id'=>$value['id']]);
                            continue;
                        }
                    }
                }
                //上传SKU图片
                $baby_shopify_img_id = $this->db->from('baby_goods_sku')->where(['baby_goods_id' => $baby_update_v['baby_goods_id']])->select('baby_shopify_img_id')->group_by('baby_shopify_img_id')->get()->result_array();
                foreach ($baby_shopify_img_id as $key => $value) {
                    if (empty($value['baby_shopify_img_id'])){
                        continue;
                    }

                    $baby_shopify_sku_id = $this->db->from('baby_goods_sku')->where(['baby_shopify_img_id' => $value['baby_shopify_img_id']])->select('baby_shopify_sku_id')->get()->result_array();
                    $variant_ids    = [];

                    foreach ($baby_shopify_sku_id as $k => $v) {
                        $variant_ids[] = $v['baby_shopify_sku_id'];
                    }
                    $res = array('image' => array('id' => $value['baby_shopify_img_id'], 'variant_ids' => $variant_ids));
                    $this->shopify_api->shopify_sku_img($info['id'], $value['baby_shopify_img_id'], $res);
                }
                $this->db->where(['id'=>$id]);
                $this->db->update('baby_shopify_goods',['shopify_id'=>$info['id']]);
            // }
                $this->db->where(['id'=>$baby_update_v['id']]);
                $this->db->update('baby_update',['is_up'=>1]);
            }
        }

        //只更新shopify图片
        public function goods_web_img(){

            $this->load->library('sys_message');
            $this->load->model('shopify_goods_model');
            $this->load->model('siteweb_model');
            $this->load->model('goods_model');
            $this->load->library('shopify_api');
            $this->load->model('tagslist_model');

            $goods_id = $this->input->post('goods_id');

            $update_web_id = $this->input->post('web_id');

            $siteweb = $this->shopify_goods_model->get_goods_siteweb_list($goods_id);
            foreach ($siteweb as $key => $value) {
                if ( !in_array($value['web_id'], $update_web_id)){
                    unset($siteweb[$key]);
                }
            }

            if (empty($siteweb)){
                $this->sys_message->wrong('商品没有上传过站点');
            }
            $goods_album = $this->db->from('goods_album')->where(['goods_id'=>$goods_id])->get()->result_array();
            //查询商品图片
            $images = array();
            foreach ($goods_album AS $row) {
                $images[] = array(
                    'src' => strpos($row['original_img'], 'https://') !== false ? $row['original_img'] : 'http://sumerbikini.com' . $row['original_img'],
                );
            }
            $data = array(

                'images'           => $images,
            );
            foreach ($siteweb as $key => $value) {
                $data['shopify_id'] = $value['shopify_id'];
                $this->shopify_api->initialize($value);
                $this->shopify_api->update_up_goods_img($data);
            }
            $this->sys_message->success('成功!');
        }
    }